package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseSingleButtonDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CertificateNoContent;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.DeleteSuccessMessage;
import com.isunland.managesystem.entity.EmployeeLoanContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.util.HashMap;
import org.apache.http.Header;
import org.json.JSONException;

public class EditEmployeePaymentFragment extends EmployeePaymentFragment {
  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";
  protected static final String TAG = EmpoyeeLoanDetailEditFragment.class.getName();
  private EmployeeLoanContent mEmployeeLoanContent;
  private String mMemberCode;// 会员编码
  private String fileName = "";// 会员编码

  @Override public void onCreate(Bundle savedInstanceState) {
    mMemberCode = CurrentUser.newInstance(getActivity()).getMemberCode();
    mEmployeeLoanContent = (EmployeeLoanContent) getArguments().getSerializable(EXTRA_VALUE);
    fileName = mEmployeeLoanContent.getFileOriginalName();//服务器返回文件名
    selcurFile = mEmployeeLoanContent.getFilePath();//服务器返回文件路径
    super.onCreate(savedInstanceState);
  }

  @Override protected void setTitle() {
    ((BaseVolleyActivity) getActivity()).getSupportActionBar()
        .setTitle(R.string.employeeRepaymentApply);
  }

  public void initData() {
    //只有草稿状态获取已有借款合计
    if ((mEmployeeLoanContent.getDataStatus()).equals(DataStatus.NEW)) {
      mSumBorrowRepayment.setText(mEmployeeLoanContent.getSumBorrow());// 当前借款合计
      getSumBorrow();//获取已有借款合计
    } else {
      mSumBorrowRepayment.setText(mEmployeeLoanContent.getSumBorrow());//当前借款合计
    }
    mCertificateNoRepayment.setText(mEmployeeLoanContent.getCertificateNo());//单据编号
    mExpenseDescRepayment.setText(mEmployeeLoanContent.getExpenseDesc());//费用摘要
    mPoutAmountRepayment.setText(mEmployeeLoanContent.getInAmount());//还款金额
    mLoanPersonRepayment.setText(mEmployeeLoanContent.getDraweeName());//还款人
    mLoanProposerRepayment.setText(mEmployeeLoanContent.getRegStaffName());//申报人
    mLoanDateRepayment.setText(mEmployeeLoanContent.getApplyTime());//申报日期
    mRepayDateRepayment.setText(mEmployeeLoanContent.getOccurDate());//还款日期
    mRepayTypeRepayment.setText(mEmployeeLoanContent.getPayModeName());//还款方式
    mrepayId = mEmployeeLoanContent.getPayModeCode();
    mrepayName = mEmployeeLoanContent.getPayModeName();

    //开户行
    etpayeeBank.setText(mEmployeeLoanContent.getPayeeBank());
    etpayeeAccname.setText(mEmployeeLoanContent.getPayeeAccname());
    etpayeeAccount.setText(mEmployeeLoanContent.getPayeeAccount());
    //附件
    if (!TextUtils.isEmpty(mEmployeeLoanContent.getFileOriginalName())) {

      mTvExtra.setText(mEmployeeLoanContent.getFileOriginalName());
      //点击附件名，下载附件
      mTvExtra.setOnClickListener(new OnClickListener() {

        @Override public void onClick(View v) {
          ExtraDownLoadDialogFragment dialog = null;
          if (TextUtils.isEmpty(mFilePath)) {
            dialog = ExtraDownLoadDialogFragment.newInstance("", selcurFile);
          } else {
            dialog = ExtraDownLoadDialogFragment.newInstance(mFilePath, "");
          }

          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.show(fm, "");
        }
      });
    }
  }

  public void getSumBorrow() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_EMPLOYEE_LOAN_DETAIL);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("certificateCode", mEmployeeLoanContent.getCertificateCode());
    params.put("userJobNo", mCurrentUser.getJobNumber());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        CertificateNoContent[] array = new Gson().fromJson(arg0, CertificateNoContent[].class);
        CertificateNoContent mNoContent = array[0];
        mSumBorrowRepayment.setText(mNoContent.getSumBorrow());//已有借款合计
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_confirm:
        Double borrowMoney = Double.parseDouble(mSumBorrowRepayment.getText().toString());
        Double payMoney = Double.parseDouble(mPoutAmountRepayment.getText().toString());
        double result = borrowMoney - payMoney;
        if (result >= 0) {
          //选择新附件
          if (!TextUtils.isEmpty(mTvExtra.getText().toString())
              && !TextUtils.isEmpty(mfileName)
              && !TextUtils.isEmpty(mFilePath)) {
            //上传新附件,首先将原始附件删除，在上传新附件
            volleyExtra();
            //					volleyDelete();
          }
          //附件为空时
          else if (TextUtils.isEmpty(mTvExtra.getText().toString())
              && TextUtils.isEmpty(mfileName)
              && TextUtils.isEmpty(mFilePath)) {
            selcurFile = "";
            mfileName = "";
            postSave();
          }
          //附件没有修改时
          else {
            postSave();
          }
        } else {
          Toast.makeText(getActivity(), R.string.errorRepayMoney, Toast.LENGTH_SHORT).show();
        }
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //删除附件
  private void volleyDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_FILE);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("selcurFile", selcurFile);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        DeleteSuccessMessage result =
            new Gson().fromJson(new String(arg0), DeleteSuccessMessage.class);
        try {

          SuccessMessage delResult = new Gson().fromJson(new String(arg0), SuccessMessage.class);
          //删除成功
          if (delResult != null && delResult.getResult() != null && result.getResult()
              .equals("1")) {
            Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
            volleyExtra();//上传新附件
          } else {
            Toast.makeText(getActivity(), "文件不存在", Toast.LENGTH_SHORT).show();
            volleyExtra();//上传新附件
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
          Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
        } catch (NotFoundException e) {
          e.printStackTrace();
          Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
      }
    });
  }

  //附件上传方法
  private void volleyExtra() {

    new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_UPLOAD_FILE,
        "r_expense_inexp_main", mEmployeeLoanContent.getId(), new myUpLoadHandler(), false);
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {
    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      //			MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.wrong_data, Toast.LENGTH_SHORT).show();
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          //					Toast.makeText(getActivity(), R.string.fileUploadSuccess, Toast.LENGTH_SHORT).show();
          // 上传成功,再上传数据
          selcurFile = result.getMessage().toString();
          selcurFile = selcurFile.replace("\\", "/");
          LogUtil.i("selcurFile==" + selcurFile);
          //上传数据
          postSave();
        } else {
          MyUtils.dismissDialog();
          //					Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
          //					//重命名，重新上传文件
          //					mDocPath=FileUtil.renameFile(mDocPath);
          //					mfileName=FileUtil.getFileNameByFilePath(mDocPath);
          //					LogUtil.i("重命名mFilePath==="+mDocPath);
          //					//刷新sd卡
          ////					MediaScannerConnection.scanFile(getActivity(), new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()+"/"+mfileName}, null,null);
          //
          //					new FileNetWorkUtil(getActivity()).upLoadFile(mDocPath, ApiConst.URL_UPLOAD_FILE, "r_expense_inexp_main",mEmployeeLoanContent.getId(), new myUpLoadHandler(), false);

          DialogFragment dialog = null;
          FragmentManager fm = getActivity().getSupportFragmentManager();
          //					dialog = BaseConfirmDialogFragment
          //							.newInstance("已上传存在同名文件,请修改文件名！",R.string.restart_title);
          dialog = BaseSingleButtonDialogFragment.newInstance(R.string.rename_file,
              R.string.restart_title);
          dialog.setTargetFragment(EditEmployeePaymentFragment.this, REQUEST_RENAME);
          dialog.show(fm, "");
        }
      } catch (JsonSyntaxException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      } catch (NotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }
    }
  }

  private void postSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PESONAL_SAVE);

    HashMap<String, String> params = new HashMap<String, String>();

    // 更新content
    mEmployeeLoanContent.setCertificateNo(mCertificateNoRepayment.getText().toString());
    mEmployeeLoanContent.setExpenseDesc(mExpenseDescRepayment.getText().toString());
    //		mEmployeeLoanContent.setPoutAmount(mPoutAmountRepayment.getText().toString());
    mEmployeeLoanContent.setInAmount(mPoutAmountRepayment.getText().toString());
    mEmployeeLoanContent.setSumBorrow(mSumBorrowRepayment.getText().toString());
    mEmployeeLoanContent.setApplyTime(mLoanDateRepayment.getText().toString());
    mEmployeeLoanContent.setOccurDate(mRepayDateRepayment.getText().toString());
    mEmployeeLoanContent.setPayModeName(mrepayName);
    mEmployeeLoanContent.setPayModeCode(mrepayId);

    //开户行
    mEmployeeLoanContent.setPayeeBank(etpayeeBank.getText().toString());
    mEmployeeLoanContent.setPayeeAccname(etpayeeAccname.getText().toString());
    mEmployeeLoanContent.setPayeeAccount(etpayeeAccount.getText().toString());

    //附件
    mEmployeeLoanContent.setFileOriginalName(mfileName);
    mEmployeeLoanContent.setFilePath(selcurFile);

    params.put("json", new Gson().toJson(mEmployeeLoanContent));
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("certificateCode", mEmployeeLoanContent.getCertificateCode());
    params.put("regJobNo", mCurrentUser.getJobNumber());
    params.put("type", "mobile");

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        SuccessMessage[] result = new Gson().fromJson(arg0, SuccessMessage[].class);
        SuccessMessage success = result[0];
        if (null == success || null == success.getResult()) {
          Toast.makeText(getActivity(), success.getMessage(), Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = success.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), success.getMessage(), Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), success.getMessage(), Toast.LENGTH_SHORT).show();

          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_RENAME) {
      return;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static EditEmployeePaymentFragment newInstance(EmployeeLoanContent employeeLoanContent) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, employeeLoanContent);
    EditEmployeePaymentFragment fragment = new EditEmployeePaymentFragment();
    fragment.setArguments(bundle);
    return fragment;
  }
}
